/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.utl.ist.isr.livetrack.ui;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import org.openide.util.lookup.Lookups;
import pt.utl.ist.isr.livetrack.server.LTServer;

/**
 * Top component which displays something.
 */
@TopComponent.Description(preferredID = "TrackerTopComponent",
iconBase = "pt/utl/ist/isr/livetrack/ui/icons/bullseye.gif",
persistenceType = TopComponent.PERSISTENCE_NEVER)
@TopComponent.Registration(mode = "bottomSlidingSide", openAtStartup = false)
public final class TrackerTopComponent extends TopComponent {

    private static final Map<String, TrackerTopComponent> instances = new HashMap<String, TrackerTopComponent>();
    private LTServer server;
    private TrackerNode node;
    private Runnable acquireRunnable = new Runnable() {

        @Override
        public void run() {
            server.getTracker().step();
        }
    };
    private Timer timer;

    public TrackerTopComponent() {
    }

    public static void openTracker(LTServer server, TrackerNode trackerNode) {
        String serverString = server.getHostname() + ":" + server.getPort();
        TrackerTopComponent feed;
        if (instances.containsKey(serverString)) {
            feed = instances.get(serverString);
        } else {
            feed = new TrackerTopComponent(server, trackerNode);
            instances.put(serverString, feed);
        }
        feed.open();
        feed.requestActive();
    }

    private TrackerTopComponent(final LTServer server, final TrackerNode node) {
        String serverString = server.getHostname() + ":" + server.getPort();
        this.server = server;
        this.node = node;
        setDisplayName("Tracker@" + serverString);
        initComponents();
        stepButton.setEnabled(false);
        continuousButton.setEnabled(false);
//        setName(NbBundle.getMessage(TrackerTopComponent.class, "CTL_TrackerTopComponent"));
        setToolTipText(NbBundle.getMessage(TrackerTopComponent.class, "HINT_TrackerTopComponent"));
        putClientProperty(TopComponent.PROP_KEEP_PREFERRED_SIZE_WHEN_SLIDED_IN, Boolean.TRUE);
        associateLookup(Lookups.singleton(node));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jToggleButton1 = new javax.swing.JToggleButton();
        jPanel2 = new javax.swing.JPanel();
        stepButton = new javax.swing.JButton();
        continuousButton = new javax.swing.JToggleButton();
        jSpinner1 = new javax.swing.JSpinner();

        org.openide.awt.Mnemonics.setLocalizedText(jToggleButton1, org.openide.util.NbBundle.getMessage(TrackerTopComponent.class, "TrackerTopComponent.jToggleButton1.text")); // NOI18N
        jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToggleButton1)
                .addContainerGap(106, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToggleButton1)
                .addContainerGap(180, Short.MAX_VALUE))
        );

        org.openide.awt.Mnemonics.setLocalizedText(stepButton, org.openide.util.NbBundle.getMessage(TrackerTopComponent.class, "TrackerTopComponent.stepButton.text")); // NOI18N
        stepButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stepButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(continuousButton, org.openide.util.NbBundle.getMessage(TrackerTopComponent.class, "TrackerTopComponent.continuousButton.text")); // NOI18N
        continuousButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                continuousButtonActionPerformed(evt);
            }
        });

        jSpinner1.setModel(new javax.swing.SpinnerNumberModel(100, 5, 1000, 1));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(stepButton)
                .addGap(101, 101, 101)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(continuousButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jSpinner1))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(stepButton)
                    .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(continuousButton)
                .addContainerGap(149, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 305, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed
        if (jToggleButton1.isSelected()) {
            server.getTracker().start();
            stepButton.setEnabled(true);
            continuousButton.setEnabled(true);
            NbBundle.getMessage(this.getClass(), "TrackerTopComponent.jToggleButton1.text2");
        } else {
            stepButton.setEnabled(false);
            continuousButton.setEnabled(false);
            server.getTracker().stop();
            NbBundle.getMessage(this.getClass(), "TrackerTopComponent.jToggleButton1.text");
        }
    }//GEN-LAST:event_jToggleButton1ActionPerformed

    private void stepButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stepButtonActionPerformed
        server.getTracker().step();
    }//GEN-LAST:event_stepButtonActionPerformed

    private void continuousButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_continuousButtonActionPerformed
        if (continuousButton.isSelected()) {
            if (timer != null) {
                timer.cancel();
            }
            timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    acquireRunnable.run();
                }
            }, 0, (Integer) jSpinner1.getValue());
        } else {
            timer.cancel();
            timer = null;
        }
    }//GEN-LAST:event_continuousButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToggleButton continuousButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JSpinner jSpinner1;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JButton stepButton;
    // End of variables declaration//GEN-END:variables

    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }
}
